<template>
  <el-dialog
    title="人员选择"
    :visible.sync="dialogVisible"
    :modal="true"
    :appendToBody="true"
    width="1100px"
    v-dialog-drag
    :close-on-click-modal="false"
    top="5vh"
    @close="handleClose()"
    @open="handleOpen()"
  >
    <div class="selected-content">
      <div v-for="item in selectionList" :key="item.username" class="item">
        <span>{{ item.realname }}</span>
        <span class="del-item-btn" @click="handleDelSelection(item)"
          ><i class="el-icon-close"></i
        ></span>
      </div>
    </div>
    <el-form :model="queryParams" ref="queryForm" @submit.native.prevent>
      <el-row :gutter="20">
        <el-col :span="7">
          <el-form-item
            label="所属部门"
            prop="branchinnercode"
            label-width="80px"
          >
            <treeselect
              v-model="queryParams.branchinnercode"
              :options="deptList"
              :show-count="true"
              placeholder="请选择部门"
              :disabled="branchSearchDisabled"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="username">
            <el-input
              v-model="queryParams.username"
              placeholder="请输入用户名/真实姓名"
              clearable
              size="small"
              @keyup.enter.native="getUserList"
            />
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item style="display: flex">
            <el-button icon="el-icon-search" size="mini" @click="getUserList"
              >查询</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <TableSelect
      ref="table"
      :data="userList"
      :selectionList.sync="selectionList"
      :selectableCallBack="selectableCallBack"
      rowKey="username"
      v-loading="tableLoading"
    >
      <el-table-column
        type="index"
        label="序号"
        width="60"
        align="center"
      ></el-table-column>
      <el-table-column
        label="成员姓名"
        align="center"
        prop="realname"
      ></el-table-column>
      <el-table-column
        label="用户名"
        align="center"
        prop="username"
      ></el-table-column>
      <el-table-column label="所在部门" align="center" prop="deptName">
        <template slot-scope="{ row }">
          {{ row.dept ? row.dept.name : "" }}
        </template>
      </el-table-column>
      <el-table-column label="所属工厂" align="center" prop="factoryDeptName">
        <template slot-scope="{ row }">
          {{ row.bizUserVo ? row.bizUserVo.factoryDeptName : "" }}
        </template>
      </el-table-column>
      <el-table-column label="所属车间" align="center" prop="workshopNames">
        <template slot-scope="{ row }">
          {{ row.bizUserVo ? row.bizUserVo.workshopNames : "" }}
        </template>
      </el-table-column>
      <el-table-column
        label="所属产线"
        align="center"
        prop="lineNames"
      >
        <template slot-scope="{ row }">
          {{ row.bizUserVo ? row.bizUserVo.lineNames : "" }}
        </template>
      </el-table-column>
      <el-table-column label="所属班组" align="center" prop="groupName">
        <template slot-scope="{ row }">
          {{ row.bizUserVo ? row.bizUserVo.groupName : "" }}
        </template>
      </el-table-column>
      <el-table-column label="工位" align="center" prop="workStationNames">
        <template slot-scope="{ row }">
          {{ row.bizUserVo ? row.bizUserVo.workStationNames : "" }}
        </template>
      </el-table-column>
      <el-table-column label="属性" align="center">
        <template slot-scope="{ row }">
          {{ identityMap[row.identity] || "" }}
        </template>
      </el-table-column>
    </TableSelect>
    <pagination
      :total="pager.total"
      :page.sync="pager.pageNum"
      :limit.sync="pager.pageSize"
      @pagination="getUserList"
    />
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="beSureSelect()">保 存</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { getUserList } from "@/api/system/user";
import { treeselect } from "@/api/system/dept";
import TableSelect from "@/components/TableSelect";
import { findTreeNode } from "@/utils/tree";
export default {
  components: { TableSelect },
  props: {
    visibles: {
      type: Boolean,
      default: false,
    },
    // 默认查询部门
    branchinnercode: {
      type: [String, Number],
      default: null,
    },
    branchinnerKey: {
      type: String,
      default: "id",
    },
    // 查询部门控件是否可修改
    branchSearchDisabled: {
      type: Boolean,
      default: false,
    },
    // 不可选回调，返回true或false，传参为user
    selectableCallBack: {
      type: Function,
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: false,
    },
    // 默认展示[{username:"",realname:""}]
    defaultValues: {
      type: Array,
      default: () => {},
    },
  },
  dicts: ["identity"],
  data() {
    return {
      queryParams: {
        branchinnercode: null,
        username: "",
      },
      deptList: [],
      userList: [],
      tableLoading: false,
      pager: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
      },
      selectionList: [],
    };
  },
  computed: {
    dialogVisible: {
      set(val) {
        this.$emit("update:visibles", val);
      },
      get() {
        return this.visibles;
      },
    },
    identityMap() {
      return this.dictToMap(this.dict.identity);
    },
  },
  methods: {
    handleClose() {
      this.queryParams = {
        branchinnercode: null,
        username: "",
      };
      this.deptList = [];
      this.userList = [];
      this.selectionList = [];
      this.tableLoading = false;
      this.pager.total = 0;
      this.pager.pageNum = 1;
    },
    async handleOpen() {
      this.selectionList = this.defaultValues?.length
        ? [...this.defaultValues]
        : [];

      // 查询部门
      await this.getDept();
      // 查询列表
      this.getUserList();
    },
    // 获取用户列表
    getUserList() {
      this.tableLoading = true;
      const { pageNum, pageSize } = this.pager;
      const { branchinnercode, username } = this.queryParams;

      const params = {
        branchinnercode,
        username,
        pageNum,
        pageSize,
      };
      getUserList(params)
        .then((res) => {
          this.userList = res.rows || [];
          this.pager.total = res.total;
          this.tableLoading = false;
        })
        .catch((err) => {
          this.tableLoading = false;
        });
    },
    //获取部门列表
    async getDept() {
      try {
        this.tableLoading = true;
        const res = await treeselect();
        this.deptList = res.data || [];
        if (this.branchinnercode) {
          // 默认搜索条件
          const item = findTreeNode(res.data, (node) => {
            return node[this.branchinnerKey] == this.branchinnercode;
          });
          this.queryParams.branchinnercode = item?.id || null;
        }
        this.tableLoading = false;
      } catch (error) {
        this.tableLoading = false;
      }
    },
    //重置
    resetQuery() {
      this.pager.pageNum = 1;
      this.queryParams.username = null;
      // 当branchinnercode筛选条件不可编辑时，重置时也重置branchinnercode
      if (!this.branchSearchDisabled) {
        this.queryParams.branchinnercode = null;
      }
      this.getUserList();
    },
    handleDelSelection(item) {
      if (!item) {
        return;
      }
      if (this.$refs.table) {
        this.$refs.table.handleDelSelection(item);
      }
    },
    beSureSelect() {
      const selection = this.selectionList;
      if (!this.multiple) {
        if (selection.length > 1) {
          this.$message({
            message: "最多选择一条数据!",
            type: "warning",
          });
          return;
        }
      }
      this.$emit("closeDialog", selection || []);
      this.dialogVisible = false;
    },
  },
};
</script>
<style lang="scss" scoped>
.selected-content {
  width: 100%;
  height: 88px;
  padding: 10px;
  border: 1px solid #dfe6ec;
  margin-bottom: 20px;
  overflow-y: auto;
  .item {
    height: 28px;
    line-height: 28px;
    margin-right: 10px;
    margin-bottom: 10px;
    padding: 0 10px;
    font-size: 14px;
    display: inline-block;
    vertical-align: middle;
    background: rgb(234, 248, 254);
    color: #409eff;
    .del-item-btn {
      margin-left: 10px;
      cursor: pointer;
    }
  }
}
::v-deep {
  .el-dialog .el-dialog__body {
    padding-top: 10px;
  }
  .el-form-item {
    margin-bottom: 15px;
  }
}
</style>
